<?php

namespace App\Models;

use App\Http\Resources\GoodsCategoryCollection;

class GoodsCategory extends Base
{
    const IS_SHOW_YES = 1; //前台展示
    const IS_SHOW_NO = 0; //不展示

    const STATUS_YES = 1; // 启用
    const STATUS_NO = 0; // 禁用

    const IS_ADMIN_YES = 1; //系统添加
    const IS_ADMIN_NO = 0; //商户添加

    const IS_SHOW_MAP = [
        self::IS_SHOW_NO => '不展示',
        self::IS_SHOW_YES => '展示',
    ];

    const STATUS_MAP = [
        self::STATUS_YES => '启用',
        self::STATUS_NO => '禁用',
    ];

    const IS_ADMIN_MAP = [
        self::IS_ADMIN_NO => '否',
        self::IS_ADMIN_YES => '是',
    ];

    protected function add($inputs)
    {
        $inputs['aid'] = auth()->id();
        $inputs['is_admin'] = self::IS_ADMIN_YES;
        $this->fill($inputs);
        $this->save();
    }

    protected function edit($inputs)
    {
        $this->where('id', $inputs['id'])->update($inputs);
    }

    protected function del($inputs)
    {
        $this->where('id', $inputs['id'])->delete();
        $this->where('pid', $inputs['id'])->delete();
    }

    protected function index($inputs)
    {
        if (isset($inputs['name']) && !empty($inputs['name'])) {
            $data = self::query()
                ->orderBy('sequence', 'desc')->select([
                    'id',
                    'pid',
                    'name',
                    'is_admin',
                    'status',
                    'is_show',
                    'sequence',
                ])->where('name', $inputs['name'])->get();
            $data = (new GoodsCategoryCollection($data))->response()->getData(true);
            return response()->json(['data' => $data['data']]);
        } else {
            $data = self::query()
                ->orderBy('sequence', 'desc')->select([
                    'id',
                    'pid',
                    'name',
                    'is_admin',
                    'status',
                    'is_show',
                    'sequence',
                ])->get();
            $data = (new GoodsCategoryCollection($data))->response()->getData(true);
            return response()->json(['data' => make_tree($data['data'])]);
        }
    }
}
